// Copyright (c) 2011 Tony Zale. All rights reserved.

/**
 * Performs a jQuery post to lookup a book at overdrive.com.
 *
 * @param author Author of the book.
 * @param title Title of the book.
 */
var base_url = 'http://crystallake.lib.overdrive.com/';
function jqueryLookup(author, title) {
  var url = base_url + 'en/BANGSearch.dll';
  $.post(url,
        {'Title':title, 'Creator':author, 'Keyword':'', 'ISBN':'', Format:420, 'Publisher':'', 'Subject':'', 'Award':'', 'CollDate':'', 'PerPage':1, 'Sort':'SoryBy%3Dtitle'}, 
        function(data, textStatus, jqXHR) { 
	    var clean_data = data.replace('<html>', '<div name="html">');
	    clean_data = clean_data.replace('</html>', '</div>');
	    var j_clean_data = $(clean_data);
	    copies_available = $("div > div", j_clean_data).filter(":contains('Available copies')").find("noscript").text().trim();
	    if (copies_available == undefined)
		return;
	    var library_name = $('title', j_clean_data)[0].innerHTML.split(' -')[0];
	    if (clean_data.indexOf('no results were found') > -1) {
		displayNotStocked(library_name);
	    }
	    else if (copies_available == "0") {
		console.log("no copies");
		amz_url = $("a[href*='ContentDetails']", j_clean_data)[0].href;
		split_amz_url = amz_url.split("/");
		lib_url = base_url + split_amz_url[split_amz_url.length - 1];
		console.log(lib_url);
		displayStocked('All copies checked out at ' + library_name + ': ', lib_url, 'Reserve');
	    } else {
		console.log("copies");
		amz_url = $("a[href*='ContentDetails']", j_clean_data)[0].href;
		split_amz_url = amz_url.split("/");
		lib_url = base_url + split_amz_url[split_amz_url.length - 1];
		console.log(lib_url);
		displayStocked('Available at ' + library_name + ': ', lib_url, 'Borrow');
	    }
	});
}

function createDOM() {
    var library_dom = document.createElement('div');
    library_dom.style.cssText = [
	'background-color: #ffd700;',
	'background-image: -webkit-repeating-linear-gradient(' +
            '45deg, transparent, transparent 35px,' +
            'rgba(0,0,0,.1) 35px, rgba(0,0,0,.1) 70px);',
	'color: #000;',
	'padding: 10px;',
	'font: 14px Arial;'
    ].join(' ');
    return library_dom;
}

function displayNotStocked(library_name) {
    var library_dom = createDOM();
    var data_dom = document.createElement('strong');
    data_dom.innerText = 'Not stocked by ' + library_name;
    library_dom.appendChild(data_dom);
    document.body.style.cssText = 'position: relative';
    document.body.parentElement.insertBefore(library_dom, document.body);
}

function displayStocked(pre_url_text, url, link_text) {
    console.log(url);
    var library_dom = createDOM();
    var data_dom = document.createElement('strong');
    data_dom.innerText = pre_url_text;
    var link_dom = document.createElement('a');
    link_dom.setAttribute('href', url)
    link_dom.innerText = link_text;
    link_dom.style.color = '#000';
    data_dom.appendChild(document.createTextNode(' '));
    data_dom.appendChild(link_dom);
    library_dom.appendChild(data_dom);
    document.body.style.cssText = 'position: relative';
    document.body.parentElement.insertBefore(library_dom, document.body);
}
var format = ($(".content ul li").filter(":contains('Format: Kindle Edition')"))[0];
console.log(format);
if (format) {
  var split_title = document.title.split(':');
    console.log(split_title);
  var book_title = split_title[1];
  book_title = book_title.substr(1, book_title.length - 7);  // skip the initial ' ', length-7 for the initial space and trailing ' eBook'.
  var author = split_title[2].substr(1);  // skip the initial ' '
  // Check for multiple authors, only use the first
  author = author.split(',')[0].split(' ');
  // Only use the author's last name.
  jqueryLookup(author[author.length -1], book_title);
}